package submarine;

import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.util.Random;

public abstract class SeaObject {
    protected int width;
    protected int height;
    protected int x;
    protected int y;
    protected int speed;
    protected static final int LIVE = 0;
    protected static final int DEAD = 1;
    protected int state = LIVE;


    public SeaObject(int width, int height, int x, int y, int speed) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.speed = speed;
    }

    public SeaObject(int width, int height, int speed) {
        this.x = -width;
        Random random = new Random();
        y = random.nextInt(World.HEIGHT - height - 150 + 1) + 150;
        this.width = width;
        this.height = height;
        this.speed = random.nextInt(speed) + 1;
    }

    /**
     * 对象是否存活
     *
     * @return boolean
     * @author xw
     */
    public boolean isLive() {
        return this.state == LIVE;
    }

    /**
     * 对象是否死亡
     *
     * @return boolean
     * @author xw
     */
    public boolean isDead() {
        return this.state == DEAD;
    }

    /**
     * 在窗口绘画对象
     *
     * @author xw
     */
    public void paintImage(Graphics g) {
        if (isLive()) {
            this.getImage().paintIcon(null, g, this.x, this.y);
        }
    }

    /**
     * 对象移动
     *
     * @author xw
     */
    public abstract void move();

    /**
     * 获取对象图
     *
     * @author xw
     */
    public abstract ImageIcon getImage();

    /**
     * 对象是否越界
     *
     * @author xw
     */
    public boolean isOutOfBounds() {
        return this.x >= World.WIDTH;
    }

    /**
     * 对象是否与参与对象发生碰撞
     *
     * @param s 参与对象
     * @return boolean
     */
    public boolean isHit(SeaObject s) {
        int x1 = this.x - s.width;
        int x2 = this.x + this.width;
        int y1 = this.y - s.height;
        int y2 = this.y + this.height;
        return (x1 <= s.x && s.x <= x2)
                &&
                (y1 <= s.y && s.y <= y2);
    }

    /**
     * 对象死亡
     *
     * @author xw
     */
    public void goDead() {
        this.state = DEAD;
    }

}
